package com.cloudxingkong.dianyinke.Student.Ui;
/**
 * 积分支付------
 */

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.bean.IntegralOrder;
import com.cloudxingkong.dianyinke.Student.bean.StudentAddr;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class CreditsExchangeDetails extends BaseActivity {
    private TextView order_tv_Name, order_tv_Phone, order_tv_arrd, order_tv_headtitle, order_tv_title, order_tv_size, order_tv_receiveTime, order_tv_useIntegral;
    private Spinner order_distribution_spinner;//配送方式
    private String distriSpinner;
    private Spinner order_pay_spinner;//支付方式
    private String paySpinner;
    private Button btn_integralPay;
    private SharedPreferences sharedPreferences;
    private static final String[] items = {"积分兑换"};
    private static final String[] item = {"快递免邮"};
    private ArrayAdapter<String> stringArrayAdapter;
    private ProgressDialog progressDialog;
    private String num;
    private String saID;
    private String goodsID;
    private List<IntegralOrder.ObjBean> list;
    private ImageView order_image;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_credits_exchange_details);
        sharedPreferences = CreditsExchangeDetails.this.getSharedPreferences("data_dyk", 0);

        init();

        queryStudentsAddress();//学生添加地址

        clickListener();//点击事件

    }

    private void queryStudentsAddress() {
        final String sessionid = CookieHelper.getSessionID(sharedPreferences);
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + StudentUri.QUERYSTUDENTADDRESS);
        params.addHeader("cookie", sessionid);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("test", "学生默认地址信息 " + result);
                Message msg = handler.obtainMessage();
                msg.what = 2;
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("test", "学生默认地址信息失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void loadData() {
        progressDialog = ProgressDialog.show(CreditsExchangeDetails.this, null, "正在加载...", true, false);
        String sessionid = CookieHelper.getSessionID(sharedPreferences);
        String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.AAAA;
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionid);
        params.addBodyParameter("addrid", saID);//地址ID
        params.addBodyParameter("goodsid", goodsID);//物品ID
        params.addBodyParameter("num", num);//购买数量
        params.addBodyParameter("exprtype", distriSpinner);//配送方式
        params.addBodyParameter("paytype", paySpinner);//支付方式
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "确认订单:" + result);
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = result;
                handler.sendMessage(message);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void clickListener() {
        btn_integralPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(CreditsExchangeDetails.this);
                builder.setTitle("确认支付")
                        .setMessage("亲，您确定要支付吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                loadData();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String state = (String) msg.obj;
                    Log.e("test", "积分兑换---" + state);
                    if (state != null && !state.equals("")) {
                        Gson gson = new Gson();
                        IntegralOrder integralOrder = null;
                        integralOrder = gson.fromJson(state, IntegralOrder.class);
                        // order_tv_title.setText(integralOrder.getObj().getName() + "");//物品名称
                        // order_tv_size.setText(integralOrder.getObj().getSize() + "");//规格
                        // order_tv_receiveTime.setText(integralOrder.getObj().getReceivetime() + "");//发货时间
                        // order_tv_useIntegral.setText(integralOrder.getObj().getTotalpoints() + "");//使用积分
                        // ImageLoader.getInstance().displayImage(integralOrder.getObj().getPic(), order_image);
                        progressDialog.dismiss();
                    }
                    break;
                case 2:
                    String result2 = (String) msg.obj;
                    Log.e("test", "学生请求地址ID " + result2);
                    if (result2 != null && !result2.equals("")) {
                        StudentAddr sa = (new Gson()).fromJson(result2, StudentAddr.class);
                        if (sa.isSuccess()) {
                            if (sa.getObj() != null) {
                                String a = sa.getObj().getPeople();
                                order_tv_Name.setText(a);
                                order_tv_Phone.setText(sa.getObj().getPhone() + "");
                                order_tv_arrd.setText(sa.getObj().getAddr() + "");
                                saID = sa.getObj().getId() + "";
                            } else {
                                Toast.makeText(CreditsExchangeDetails.this, "您尚未添加地址", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(CreditsExchangeDetails.this, "请求地址失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }

    };

    private void init() {
        list = new ArrayList<>();
        order_tv_Name = (TextView) findViewById(R.id.order_tv_Name);//收货人名字
        order_tv_Phone = (TextView) findViewById(R.id.order_tv_Phone);//收货人电话
        order_tv_arrd = (TextView) findViewById(R.id.order_tv_arrd);//收货人地址
        order_image = (ImageView) findViewById(R.id.order_image);//商品图片
        order_tv_headtitle = (TextView) findViewById(R.id.order_tv_headtitle);//投头题
        order_tv_title = (TextView) findViewById(R.id.order_tv_title);//商品名称
        order_tv_size = (TextView) findViewById(R.id.order_tv_size);//规格大小
        order_tv_receiveTime = (TextView) findViewById(R.id.order_tv_receiveTime);//发货时间
        order_tv_useIntegral = (TextView) findViewById(R.id.order_tv_useIntegral);//使用积分
        order_pay_spinner = (Spinner) findViewById(R.id.order_pay_spinner);
        order_distribution_spinner = (Spinner) findViewById(R.id.order_distribution_spinner);
        btn_integralPay = (Button) findViewById(R.id.btn_integralPay);
        //spinner
        stringArrayAdapter = new ArrayAdapter<String>(this, android.support.v7.appcompat.R.
                layout.support_simple_spinner_dropdown_item, items);
        order_pay_spinner.setAdapter(stringArrayAdapter);
        stringArrayAdapter = new ArrayAdapter<String>(this, android.support.v7.appcompat.R.
                layout.support_simple_spinner_dropdown_item, item);
        order_distribution_spinner.setAdapter(stringArrayAdapter);

        paySpinner = order_pay_spinner.getSelectedItem().toString();//支付
        distriSpinner = order_distribution_spinner.getSelectedItem().toString();//配送方式

        Intent intent = getIntent();
        num = intent.getStringExtra("num");
        goodsID = intent.getStringExtra("goodsID");
        order_tv_title.setText(intent.getStringExtra("goodsTitle"));
        order_tv_size.setText(intent.getStringExtra("goodsGuige"));
        order_tv_receiveTime.setText(intent.getStringExtra("goodsAsTime"));
        order_tv_useIntegral.setText(intent.getStringExtra("points"));
        ImageLoader.getInstance().displayImage(intent.getStringExtra("goodsPic"), order_image);
    }

    public void order_map(View view) {
        Intent intent = new Intent(this, AMapForStudent.class);
        startActivity(intent);
    }

    public void order_fanhui(View view) {
        finish();
    }
}
